﻿import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
import Box2D 2.0
import "./shared"

Item {
    id: screen
    width: 350
    height: 1040

    Component.onCompleted: {
    }

    property var items: new Array
    property int num: 0
    property alias imgFix: four
    property bool isChange: false
    property var lastPoly: undefined
    property var listItems: new Array

    function addPolygon(list){
        if(isChange){
            isChange = false
            if(lastPoly != undefined){
                lastPoly.vertices = list
            }
        }
        else{
            var poly = polygon.createObject(screen)
            poly.vertices = list
            imgFix.addFixture(poly)
            lastPoly = poly
            listItems.push(poly)

            imgFix.gravityScale = 1

            listMode.append({"name": "第" + listItems.length + "次"})

            imgFour.x = itemRight.x + 10
            imgFour.y = 10
        }
    }
    function clickList(){
        btnSave.text = "change "+ (listView.currentIndex+1)
        lastPoly = listItems[listView.currentIndex]
        isChange = true

        for(var i in items){
            items[i].destroy()
        }
        items.length = 0

        var vet = lastPoly.vertices

        for(var j in vet){

            var obj = ball.createObject(img)
            obj.x = vet[j].x - obj.width/2
            obj.y = vet[j].y - obj.height/2
            obj.myIndex = j
            items.push(obj)
        }
    }

    Component{
        id: polygon

        Polygon {
            friction: 0.2
            density: 0.1
            restitution: 0
            vertices: [
            ]
        }
    }

    Component{
        id: ball
        Rectangle{
            id: rect

            property int myIndex: 0
            z: 10
            radius: 50
            width: 6
            height: 6
            color: "green"
            border.color: "lightblue"
            smooth: true
            opacity: 0.5
            onXChanged: {
                if(x<-10 || x>img.width+10){
                    visible = false
                    for(var i in items){
                        if(items[i].myIndex == myIndex){
                            items[i].destroy()
                            items.splice(i,1)
                            break
                        }
                    }
                }
            }

            MouseArea{
                anchors.fill: rect
                drag.target: rect
                propagateComposedEvents: true
                onClicked: {
                }
            }
        }


    }

    Row{
        y: 15
        width: btn.width
        height: btn.height
        z: 1000
        Button{
            id: btn
            text: "openpix"
            onClicked: {
                fileDialog.visible = true
            }
        }
        Button{
            text: "图片归零"
            onClicked: {
                img.scale = 1
                img.x = 0
                img.y = 0
                //clear dian
                 for(var i in items){
                     items[i].destroy()
                 }
                 items.length = 0
            }
        }
        Button{
            id: btnSave
            text: "add"
            onClicked: {
                btnSave.text = "add"
                textinput.text = ""
                var list = new Array
                for(var i in items){
    //                console.log(i,items[i].x+items[i].width/2,items[i].y+items[i].height/2)
                    var x = Number(items[i].x+items[i].width/2).toFixed(2)
                    var y = Number(items[i].y+items[i].height/2).toFixed(2)

//                    console.log("Qt.point("+x+","+y+"),")
                    textinput.text += "Qt.point("+x+","+y+"),\n"

                    list.push(Qt.point(x,y))
                }
                addPolygon(list)
            }
        }

        Button{
            text: "deleteList"
            onClicked: {
                listItems[listView.currentIndex].destroy()
                listMode.remove(listView.currentIndex,1)
                listView.currentIndex = 0
                isChange = false
            }
        }
        Button{
            text: "debugWorld"
            onClicked: {
                debug.visible = !debug.visible
            }
        }
        Button{
            text: "printLog"
            onClicked: {
                textinput.text = ""
                for(var i in listItems){
                    var ver = listItems[i].vertices
                    for(var j in ver){
                        var x = ver[j].x
                        var y = ver[j].y
                        textinput.text += "Qt.point(" + x + "," + y + ")," + "\n"
                    }
                    textinput.text += "\n"
                }

                console.log("log:",textinput.text)
            }
        }
    }


    FileDialog {
        id: fileDialog
        title: "Please choose a file"
        folder: widget.getCurrentPath() + "/"
        onAccepted: {
            console.log("You chose: " + fileDialog.fileUrl)
            img.source = fileDialog.fileUrl
            imgFour.source = img.source

            for(var i=0;i<items.length;i++){
                items[i].visible = false
                items[i].destroy()
            }
            items.length = 0
        }
    }

    Rectangle{
        id: itemImg
        y: 50
        width: 400
        height: parent.height - y - 20
        clip: true
        color: "gray"

        MouseArea{
            id: bgMouse
            anchors.fill: parent
            propagateComposedEvents: true

            onWheel: {
                wheel.accepted = true
                if(wheel.angleDelta.y > 0){
                    img.scale += 0.1
                }
                else{
                    if(img.scale <= 0.1) {
                        img.scale=0.1
                        return
                    }
                    img.scale -= 0.1
                }
            }
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            drag.target: img
            onClicked: {
            }
        }

        Rectangle{
            x: img.x
            y: img.y
            width: img.width
            height: img.height
            scale: img.scale
            color: "lightgray"
            opacity: 0.5
            transformOrigin: Item.Center
        }

        Image {
            id: img
            source: ""
            smooth: true
            transformOrigin: Item.Center
            onScaleChanged: {
//                console.log(x,y)
            }

            MouseArea{
                anchors.fill: img
                propagateComposedEvents: true
                onClicked: {
                    var obj = ball.createObject(img)
                    obj.x = mouseX - obj.width/2
                    obj.y = mouseY - obj.height/2
                    obj.myIndex = num
                    items.push(obj)
                    num++
                }
            }
        }

    }


    Rectangle{
        id: rectLog
        x: 405
        y: itemImg.y
        width: 250
        height: 150
        color: Qt.rgba(1,1,0,0.3)
        clip: true

        TextEdit{
            id: textinput
            anchors.fill: parent
            selectByMouse: true
            wrapMode: TextEdit.Wrap

        }
    }
    Rectangle{
        id: rectList
        x: rectLog.x
        y: rectLog.y + rectLog.height + 5
        width: 250
        height: 250
        color: Qt.rgba(1,0,1,0.3)
        clip: true

        ListView{
            id: listView
            width: parent.width
            height: parent.height
            delegate: Text{
                text: name
                width: listView.width
                MouseArea{
                    anchors.fill: parent
                    onClicked: {
                        listView.currentIndex = index
                        clickList()
                    }
                }
            }
            model: ListModel{
                id: listMode
            }
            highlight: Rectangle{
                width: listView.width
                height: 12
                color: "lightgray"
            }
        }

    }

    Text {
        id: texttips
        anchors.left: rectList.left
        anchors.top: rectList.bottom
        anchors.topMargin: 10
        width: rectList.width
        wrapMode: Text.Wrap
        text: qsTr("鼠标右键拖拽，左键点击，滚轮缩放，拖拽原点离开图片就是删除")
    }

    ////

    World { id: physicsWorld }



    Body {
        id: anchor
        world: physicsWorld
    }

    MouseJoint{
        id: mouseJoint
        bodyA: anchor
//         bodyB: four.body
        dampingRatio: 0.1
        maxForce: 100
    }

    Item{
        id: itemRight
        width: parent.width - rectLog.x - rectLog.width
        height: parent.height
        anchors.right: parent.right
    }

    Image{
        id: imgFour
        x: itemRight.x + 10
        y: 10
        width: sourceSize.width
        height: sourceSize.height
        smooth: true

        property alias body: four

        Body {
            id: four
            target: imgFour
            world: physicsWorld
            bodyType: Body.Dynamic
            sleepingAllowed: false
            gravityScale: 0
        }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: itemRight
        propagateComposedEvents: true
        acceptedButtons: Qt.LeftButton | Qt.RightButton

        onPressed: {
            mouseJoint.maxForce = four.getMass() * 500;
            mouseJoint.target = Qt.point(mouseX + itemRight.x, mouseY);
            mouseJoint.bodyB = four;

        }

        onPositionChanged: {
            mouseJoint.target = Qt.point(mouseX + itemRight.x, mouseY);
        }

        onReleased: {
            mouseJoint.bodyB = null;
        }
    }

    ScreenBoundaries{}

    DebugDraw {
        id: debug
        world: physicsWorld
        opacity: 0.75
//        visible: false
    }
}
